from modules.common import d_common
import gettext
from modules.common import getsource
from common.iniconfig import iniconfig
import urllib2,urllib
import os,re,zipfile
import cPickle as p
import md5
import sys
from modules.common import delete_file_folder
from modules.Chinese_English.dict_Chinese_Englishoption import dict_Chinese_Englishoption
class d_Chinese_English_re:
    word=""
    ct=""
    dt=""
    es=""
    
    def __init__(self,word):
	for uchar in word.replace(" ",""):
	    if not(uchar >= u'\u4e00' and uchar<=u'\u9fa5'):
		raise UnicodeError
	self.word=word
            
    def __del__(self):
        pass
    def _get_ct(self,source):
	a=source.find('<div id="en-simple-means" class="tab en-simple-means dict-en-simplemeans-word">')
	b=source.find('<div class="source">',a)
	if a!=-1:
	    self.ct=source[a:b]
	else:
	    a=source.find('<div id="en-simple-means" class="tab en-simple-means dict-en-simplemeans-char">')
	    b=source.find('<div class="source">',a)	  
	    self.ct=source[a:b]
	
	pattern=re.compile(r'''<a href="#[0-9]*">''')
	self.ct=pattern.sub(" ",self.ct).replace("]","]&nbsp;&nbsp;&nbsp;")                        	
	
    def get_ct(self):
	return self.ct
    
    def _get_dt(self,source):
	a=source.find('<div id="en-synthesize-means" class="tab en-synthesize-means dict-en-synthesizemeans-word">')
	b=source.find('<div class="source">',a)
	if a!=-1:
	    self.dt=source[a:b]
	else:
	    a=source.find('<div id="en-synthesize-means" class="tab en-synthesize-means dict-en-synthesizemeans-char">')
	    b=source.find('<div class="source">',a)	
	    self.dt=source[a:b]
	pattern=re.compile(r'''<a href="#[0-9]*">''')
	self.dt=pattern.sub(" ",self.dt).replace("]","]&nbsp;&nbsp;&nbsp;")	
	
    def get_dt(self):
	return self.dt
    
    def _get_es(self,source):
	    pattern1=re.compile(r'''var example_data =(.*)]];''')
	    match1=pattern1.findall(source)
	    if match1:
		    temp=[]
		    temp1=[]
		    a=""
		    match=match1[0]
		    match=match[2:]
		    match2=match.split(r"],[[[")
		    for m in match2:
			    temp.append(r'['+m)
		    for m in temp:
			    match3=m.split(r"]],[[")
			    x=match3[0]+r"]"
			    y=r"["+match3[1]
			    pattern4=re.compile(r'\["(.*?)",')
			    match4=pattern4.findall(x)
			    match5=pattern4.findall(y)
			    for m in match4:
				    a=a+m+" "
			    a=a[:-1]
			    temp1.append(a)                
			    a=""
			    for m in match5:
				    a=a+m+" "
			    a=a[:-1]
			    temp1.append(a)   
			    a=""
		    
		    i=0
		    a="<ul>"
		    for m in temp1:
			    i=i+1
			    if i%2==1:
				    a=a+"<li>"+m.replace(" ","")
			    else:
				    a=a+"<br>"+m+"<br></li>"
		    a=a+"</ul>"
		    a=a.replace("\\'","'").replace('\\"','"').replace("\\\\","\\").replace(self.word,"<font color=Red><strong>%s</strong></font>"%self.word)
		    self.es=a                                     
	
	
    def get_es(self):
	return self.es
    
    def analyse(self):
	url="http://dict.baidu.com/s?wd=%s" % self.word
	url=url.encode('utf-8')
	url=urllib2.unquote(url)
	source=unicode(urllib2.urlopen(url).read(),"utf-8")	

	self._get_ct(source)
	self._get_dt(source)
	self._get_es(source)
	
    def __getitem__(self,key):
	if key=="Word":
	    return self.word
	if key=="Concise translate":
	    return self.ct
	if key=="Detailed translate":
	    return self.dt
	if key=="Example Sentence":
	    return self.es	


class d_Chinese_English(d_common):
    cont=[]
    cont_en=[]
    def __init__(self):
        d_common.__init__(self,_("Chinese_English"),_("all data is from baidu"),_("hzh"),_("v1.0.0"),_("2013-2-10"))
	self.cont.append(_("Word"))
	self.cont.append(_("Concise translate"))
	self.cont.append(_("Detailed translate"))
	self.cont.append(_("Example Sentence"))

	self.cont_en.append("Word")
	self.cont_en.append("Concise translate")
	self.cont_en.append("Detailed translate")
	self.cont_en.append("Example Sentence")
	self.Chinese_English_ini=iniconfig("modules/Chinese_English/settings")
	pathzip="modules/Chinese_English/downloads/Chinese_English_data.zip"
	if not os.path.exists(pathzip):
		tmp=zipfile.ZipFile(pathzip,"w")
		tmp.close()
		self.zip_file=zipfile.ZipFile(pathzip,"a")
		self.zip_list=self.zip_file.namelist()
	else:
		self.zip_file=zipfile.ZipFile(pathzip,"a")
		self.zip_list=self.zip_file.namelist()
		
    def __del__(self):
	try:
	    self.zip_file.close()
	    delete_file_folder("modules/Chinese_English/downloads","Chinese_English_data.zip")
	except Exception,e:
	    pass

	    
    def __str__(self):
        return d_common.__str__(self)
    
    def setoptiongui(self,parent):
	    a=dict_Chinese_Englishoption(parent)
	    a.ShowModal()

	
    def setoption(self,op,val):
	    self.Chinese_English_ini.set_item(op,val)
	    
    def getoption(self,op):
	    return self.Chinese_English_ini.get_item(op)
	
    def getmp3(self,word,parent):
	    parent.m_statusBar1.SetStatusText(_("'%s' has no mp3 sound.")% word,0)
	
    def get_li(self,name,str):
	    if str==None:
		    return ""
	    if str.strip()=="":
		    return ""
	    else:
		    return '''<li><font color=Blue><h3>%s</h3></font><br/>%s</li>''' % (name,str)
    def getwordlist(self):
	    a=open("modules/Chinese_English/words.txt","r")
	    b=[]
	    for i in a.readlines():
		b.append(unicode(i,"gb2312"))
	    a.close()
	    return b
    def getcontentHTML(self,word):
	    path="modules/Chinese_English/downloads/%s" % word
	    if os.path.exists(path):
		    temp2=file(path,"r")
		    temp=p.load(temp2)
		    temp2.close()
	    else:
		    if word in self.zip_file.namelist():
			    self.zip_file.extract(word,"modules/Chinese_English/downloads/")
			    temp3=file(path,"r")
			    temp=p.load(temp3)
			    temp3.close()		    
		    else:
			    temp=d_Chinese_English_re(word)
			    temp.analyse()					
            
	    
	    a='''<h1>%s</h1><br/>
	    <ul>
	    %s%s%s
	    </ul>
	    ''' % (temp[self.cont_en[0]],
	           self.get_li(self.cont[1],temp[self.cont_en[1]]),
	           self.get_li(self.cont[2],temp[self.cont_en[2]]),
	           self.get_li(self.cont[3],temp[self.cont_en[3]]))
	    if self.getoption("auto_save").strip()=="1":
		    if word in self.zip_file.namelist():
			    return a
		    
		    b={self.cont_en[0]:temp.word,self.cont_en[1]:temp.ct,self.cont_en[2]:temp.dt
		                  ,self.cont_en[3]:temp.es}
		    self.zip_file.writestr(word,p.dumps(b),zipfile.ZIP_DEFLATED)
		    self.zip_list.append(word)
		    del b
	    return a
    def download(self,input,output,has_mp3,append,word_start=0,mp3_start=0):
	if has_mp3:
	    print _("\n**warning:Chinese_English dict doesn't support downloading mp3 files.**\n")
	if append:
		tmp=zipfile.ZipFile(output,"a")
	else:
		tmp=zipfile.ZipFile(output,"w")
		if os.path.exists(output+".project"):
			os.remove(output+".project")
	hehe=iniconfig(output+".project")	
	a=open(input,"r")
	b=a.readlines()
	allnums=len(b)
	for i in range(0,allnums):
	    b[i]=unicode(b[i],"gb2312")
	if hehe.get_item("word")!="":
		if str(md5.new(a.read()).digest())!= hehe.get_item("md5"):
			print _("\n**error:Project file %s refers to another file,please remove it.**\n") % output+".project"
			return
		word_start=string.atoi(hehe.get_item("word"))
	else:
		hehe.set_item("md5",str(md5.new(a.read()).digest()))
	a.close()	
	print _("Begin downloading words' data\n")
	try:
		for c in range(word_start,allnums):
			b[c]=b[c].strip()
			if b[c]=="":
				continue
			percent=100*(c+1)/allnums
			print _("current word:")+b[c]+" "*(25-len(b[c])) +_("percent:")+str(percent)+"%",
			sys.stdout.write("\r")
			try:
				temp=d_Chinese_English_re(b[c])
				temp.analyse()			
				d={self.cont_en[0]:temp.word,self.cont_en[1]:temp.ct,self.cont_en[2]:temp.dt
		                      ,self.cont_en[3]:temp.es}		
				tmp.writestr(b[c],p.dumps(d),zipfile. ZIP_DEFLATED)
			except KeyboardInterrupt,e:
				print _("\nDownload is canceled by user.\n")
				tmp.close()
				return			
			except:
				pass
			hehe.set_item("word",str(c+1))
		print _("\nAll words' data downloads successfully!\n")
		print _("In all, the zip file should be placed in modules/Chinese_English/downloads directory,\nand named 'Chinese_English_data.zip'\n")
	except KeyboardInterrupt,e:
		print _("\nDownload is canceled by user.\n")
		tmp.close()
		return
	os.remove(output+".project")
	tmp.close()

	
